package com.yan.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yan.common.to.mq.SeckillOrderTo;
import com.yan.common.utils.R;
import com.yan.common.vo.MemberResponseVo;
import com.yan.gulimall.seckill.feign.CouponFeignService;
import com.yan.gulimall.seckill.feign.ProductFeignService;
import com.yan.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.yan.gulimall.seckill.service.SeckillService;
import com.yan.gulimall.seckill.to.SecKillSkuRedisTo;
import com.yan.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.yan.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedissonClient redissonClient;


    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    /**
     * 定时上架.
     */
    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 扫描需要参与秒杀的活动
        R session = couponFeignService.getLatest3DaysSession();
        if (session.getCode() == 0) {
            // 上架商品
            List<SeckillSessionWithSkus> data = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            // 缓存活动信息和活动关联的商品信息到redis中
            saveSessionInfos(data);
            saveSessionSkuInfos(data);

        }
    }

    public List<SecKillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentTimeSkus方法被限流了....");
        return null;
    }

    /**
     * 返回当前时间可以参与秒杀的商品信息
     * 使用注解和try catch都可以定义受保护的资源
     * 使用注解时可以指定blockHandler和fallback
     * blockHandler: 函数会在原方法触发限流/降级/熔断时被调用
     * fallback: 函数会在触发异常时被调用
     * @return
     */
    @SentinelResource(value = "getCurrentTimeSkus", blockHandler = "blockHandler")
    @Override
    public List<SecKillSkuRedisTo> getCurrentTimeSkus() {
        // 确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();

        try (Entry entry = SphU.entry("CurrentTimeSkus")) {
            // 获取这个场次所需的秒杀信息
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);

                if (time >= start && time <= end) {
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                            SecKillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SecKillSkuRedisTo.class);
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流,{}",e.getMessage());
        }

        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSecKillInfo(Long skuId) {

        // 找到所有需要秒杀的key信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();

        if (keys != null && keys.size() < 0) {
            String regex = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regex, key)) {
                    String jsonStr = hashOps.get(key);
                    SecKillSkuRedisTo redisTo = JSON.parseObject(jsonStr, SecKillSkuRedisTo.class);

                    // 判断随机码
                    Long nowTime = new Date().getTime();
                    Long startTime = redisTo.getStartTime();
                    if (nowTime >= startTime && nowTime <= redisTo.getEndTime()) {

                    } else {
                        redisTo.setRandomCode(null);
                    }

                    return redisTo;
                }
                ;
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {

        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        // 获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if (ObjectUtils.isEmpty(json)) {
            return null;
        } else {
            // 成功逻辑
            SecKillSkuRedisTo redisData = JSON.parseObject(json, SecKillSkuRedisTo.class);
            // 校验合法性
            Long startTime = redisData.getStartTime();
            Long endTime = redisData.getEndTime();
            long time = new Date().getTime();
            long ttl = endTime - time;
            // 校验秒杀时间是否合法
            if (time >= startTime && time <= endTime) {
                // 校验随机码和商品id是否正确
                String randomCode = redisData.getRandomCode();
                String skuId = redisData.getPromotionSessionId() + "_" + redisData.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    // 数据合法,验证购物数量是否合理
                    if (num <= redisData.getSeckillLimit()) {
                        // 验证这个人是否已经购买过(幂等性)
                        // setNx
                        String redisKey = memberResponseVo.getId() + "_" + skuId;
                        // 自动过期->截止到秒杀结束
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            // 占位成功,说明未参与过秒杀 -> 获取信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                            boolean b = semaphore.tryAcquire(num);
                            // 秒杀成功发送给MQ
                            if (b) {
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setMemberId(memberResponseVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setSkuId(redisData.getSkuId());
                                seckillOrderTo.setSeckillPrice(redisData.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                return timeId;
                            }
                            return null;

                        } else {
                            // 占位失败,说明已经参与过秒杀
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }

        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> data) {
        data.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);

            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }

        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> data) {
        data.stream().forEach(session -> {
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                String token = UUID.randomUUID().toString().replace("-", "");

                if (!ops.hasKey(seckillSkuVo.getSkuId().toString())) {
                    // 缓存商品
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                    // sku的基本数据
                    R skuInfo = productFeignService.info(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }

                    // sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    // 设置当前商品的秒杀信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    // 为秒杀商品设置随机码
                    redisTo.setRandomCode(token);

                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getSkuId().toString(), jsonString);
                }


                if (!redisTemplate.hasKey(SKU_STOCK_SEMAPHORE + token)) {
                    // 为了阻止大量的并发导致的宕机,给Redis中的商品设置信号量
                    // 信号量作用:只有能成功解锁库存的线程能操作数据库,其他不能解锁库存的短时间阻塞后将直接返回
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 使用库存作为信号量来限流
                    semaphore.trySetPermits(seckillSkuVo.getSeckillSort());
                }
            });
        });
    }


}
